﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class Manage_basisset_Class : AdminPageBase
{
    private string SearchWord;
    private string returnURL;
    private int SearchFlag;
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        if (!IsPostBack)
        {

            // 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "ClassId");
            this.GridView1.Attributes.Add("SortDirection", "ASC");
            getParam();
            if (SearchFlag == 1)
            {
                GridViewBind(); 
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ClassId");
                dt.Columns.Add("Code");
                dt.Columns.Add("ClassTypeId");
                dt.Columns.Add("ClassTypeName");
                dt.Columns.Add("Name");
                dt.Columns.Add("Time");
                dt.Columns.Add("IsValidDesc");
                dt.Columns.Add("IsValid");
                dt.Columns.Add("PassScore");
                dt.Columns.Add("");

                GridviewControl.GridViewDataBind(this.GridView1, dt);
                GridviewControl.ResetGridView(this.GridView1);
            }
           // GridViewBind();
            if (add == 1)
            {
               addclass.Enabled = true;
              
            }
            else
            {
                addclass.Enabled = false;
               
            }
         
        }
    }
    private void getParam()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["SearchWord"]))
        {
            SearchWord = Request.QueryString["SearchWord"];
            txtkeyword.Text = SearchWord;
        }
        if (!string.IsNullOrEmpty(Request.QueryString["SearchFlag"]))
            SearchFlag = Convert.ToInt32(Request.QueryString["SearchFlag"]);

    }
   
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }


    }

    protected void GridViewBind()
    {

        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchClass(keyword, pager1.PageSize, pager1.CurrentPageIndex, sortExpression, sortDirection);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
               
                GridviewControl.GridViewDataBind(this.GridView1, ds.Tables[0]);

               // this.GridView1.DataSource = ds.Tables[0];
               // this.GridView1.DataBind();
                pager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0]["qty"]);
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ClassId");
                dt.Columns.Add("Code");
                dt.Columns.Add("ClassTypeId");
                dt.Columns.Add("ClassTypeName");
                dt.Columns.Add("Name");
                dt.Columns.Add("Time");
                dt.Columns.Add("IsValidDesc");
                dt.Columns.Add("IsValid");
                dt.Columns.Add("PassScore");
                dt.Columns.Add("");

                GridviewControl.GridViewDataBind(this.GridView1, dt);
                pager1.RecordCount = 0;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtkeyword.Focus();
        }

    }
  

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            e.Row.Cells[0].Attributes.Add("class", "text"); 
        }
      
    }

   
   
    protected void pager1_PageChanged(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
        this.GridView1.Attributes["SortDirection"] = sortDirection;

        this.GridViewBind();
    }



    protected void btnexport_Click(object sender, EventArgs e)
    {
        DataTable dt = GetExportData();
        if (GridView1.Rows.Count == 1 && GridView1.Rows[0].Cells[0].Text == GridviewControl.EmptyText)
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有数据，不需要导出吧！"), false);
        else
        // ExcelExport(GetStringWriter(dt), "课程.xls");
        {
            string style = @"<style> .text { mso-number-format:\@;color:#000000 } </style> ";

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("课程.xls", System.Text.Encoding.GetEncoding("utf-8")));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridView1.Columns[6].Visible = false;
            GridView1.AllowPaging = false;
            GridView1.AllowSorting = false;
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.RenderControl(htw);

            // Style is added dynamically
            Response.Write(style);

            Response.Write(sw.ToString());

            Response.End();
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
    protected DataTable GetExportData()
    {
        DataTable dt = new DataTable();
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchClass(keyword, pager1.PageSize, 0, sortExpression, sortDirection);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                dt = ds.Tables[0];

            }
        }
        return dt;

    }
	public override void VerifyRenderingInServerForm(Control control)
	{

	}

    protected void ExcelExport(StringWriter sw, string exportFileName)
    {

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.GetEncoding("utf-8")));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        // HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\" />");
        HttpContext.Current.Response.Write(sw.ToString()); 
        HttpContext.Current.Response.End();

    }
    //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
    public static StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();
		string style = @"<style>.text{ mso-number-format:\@;}</style>"; 
	    sw.WriteLine(style);//使用定义的strStyle方式写入
        //先写列的表头，这样保证如果没有数据也能输出列表头 
        sw.Write("课程编号" + "\t ");
        sw.Write("课程类型" + "\t ");
        sw.Write("课程名称" + "\t ");
        sw.Write("课程小时数" + "\t ");
        sw.Write("上传课程用户Id" + "\t ");
        sw.Write("是否有效Id" + "\t ");
        sw.Write("通过分数" + "\t ");
        sw.Write(sw.NewLine);

        //如果包含数据 
        if (dt != null)
        {
            //写数据 
            foreach (DataRow dr in dt.Rows)
            {
                sw.Write(dr["Code"].ToString() + "\t ");
                sw.Write(dr["ClassTypeName"].ToString() + "\t ");
                sw.Write(dr["Name"].ToString() + "\t ");
                sw.Write(dr["Time"].ToString() + "\t ");
                sw.Write(dr["UserId"].ToString() + "\t ");
                sw.Write(dr["IsValidDesc"].ToString() + "\t ");
                sw.Write(dr["PassScore"].ToString() + "\t ");
                //换行 
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    }


    protected void addclass_Click(object sender, EventArgs e)
    {
        int flag = 0;
        if (GridView1.Rows.Count > 0)
            flag = 1;
        returnURL = "Class.aspx?MenuId=" + MenuId + "&SearchWord=" + txtkeyword.Text.Trim() + "&SearchFlag=" + flag;
        Response.Redirect("ClassDetail.aspx?returnURL=" + Server.UrlEncode(returnURL));
       // Response.Redirect("ClassDetail.aspx?MenuId="+MenuId);
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            int fg = 0;
            if (GridView1.Rows.Count > 0)
                fg = 1;
            returnURL = "Class.aspx?MenuId=" + MenuId + "&SearchWord=" + txtkeyword.Text.Trim() + "&SearchFlag=" + fg;
            Response.Redirect("ClassDetail.aspx?id=" + e.CommandArgument.ToString() + "&returnURL=" + Server.UrlEncode(returnURL));
        }
        else if (e.CommandName == "Delete")
        {
            int flag = 0;
            int id = Convert.ToInt32(e.CommandArgument.ToString());
            string name = ((Label)GridView1.Rows[GridView1.SelectedIndex].FindControl("lblname")).Text;
            string code = ((Label)GridView1.Rows[GridView1.SelectedIndex].FindControl("lblcode")).Text;
            decimal Time = Convert.ToDecimal(((Label)GridView1.Rows[GridView1.SelectedIndex].FindControl("lblTime")).Text);
            int UserId = Convert.ToInt32(((Label)GridView1.Rows[GridView1.SelectedIndex].FindControl("lblUserId")).Text);
            int typeId = Convert.ToInt32(((HiddenField)GridView1.Rows[GridView1.SelectedIndex].FindControl("hidTypeId")).Value);
            int IsValid = Convert.ToInt32(((HiddenField)GridView1.Rows[GridView1.SelectedIndex].FindControl("hdfIsValid")).Value);
            decimal PassScore = Convert.ToDecimal(((Label)GridView1.Rows[GridView1.SelectedIndex].FindControl("lblPassScore")).Text);
            flag = jtDataAccess.OpClass(JTDataAccess.OpType.Delete, id, typeId, code, name, Time, UserId, IsValid, PassScore,"","","","");

            switch (flag)
            {

                case -1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该课程已经在使用，不允许删除！"), false);
                    break;
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                    break;
            }
       }
    }
}